package org.jeecg.modules.miniAppMerchantEndPoint.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.jx.utils.JxCryptUtil;
import org.jeecg.modules.miniAppCustomerEndPoint.constant.JxCustomerConstant;
import org.jeecg.modules.platformMasterEndPoint.entity.JxStoreRepositoryDo;
import org.jeecg.modules.platformMasterEndPoint.mapper.JxStoreRepositoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static org.jeecg.modules.miniAppMerchantEndPoint.constant.JxMerchantMiniAppConstants.*;

@RestController
@RequestMapping("/jx/merchant")
public class JxMerchantLoginController {

    @Autowired
    private JxStoreRepositoryMapper jxStoreRepositoryMapper;

    @Autowired
    private JxCryptUtil jxCryptUtil;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 接口1.1 商户使用 手机号和密码登录
     * @param requestBody
     * @return
     */
    @ApiOperation("登录")
    @GetMapping("/login")
    public Result<?> login(@RequestBody() JSONObject requestBody) {
        String phone = requestBody.getString("phone");
        String pass = requestBody.getString("pass");
        List<JxStoreRepositoryDo> jxStoreRepositoryDos = jxStoreRepositoryMapper.selectList(new LambdaQueryWrapper<JxStoreRepositoryDo>().eq(JxStoreRepositoryDo::getMerchantPhone, phone));
        if (jxStoreRepositoryDos != null && jxStoreRepositoryDos.size() > 0) {
            JxStoreRepositoryDo jxStoreRepositoryDo = jxStoreRepositoryDos.get(0);
            if (!jxCryptUtil.decryptMerchantPassword(jxStoreRepositoryDo.getMerchantLoginPasswd()).equalsIgnoreCase(pass)) {
                return Result.error("密码或账号不对");
            }

            // 将店铺id 编码到 token中
            String token = this.generateToken(jxStoreRepositoryDo.getId());
            JSONObject resultData = new JSONObject();
            // 将商户登录后分发的token保存在redis中，key为 jx_merchant_miniapp_token_15011111111，value为 token字符串
            redisUtil.set(MERCHANT_LOGIN_TOKEN_PREFIX + phone, token);

            resultData.put("token", token);
            resultData.put("storeId", jxStoreRepositoryDo.getId());
            return Result.ok(resultData);
        } else {
            return Result.error("账号或密码不对");
        }
    }

    public String generateToken(String account) {
        // 生成token
        String token = JwtUtil.sign(account, JxCustomerConstant.JX_USER_LOGIN_PASSWORD);

        // 设置token缓存有效时间
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
        redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);

        return token;
    }
}
